#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert

import binascii
import ecdsa
import os
import base58check
from _pysha3 import keccak_256

from keyTree import *


class addrTRX():
    def __init__(self, obj):
        self.obj = obj
    
    def getWallet(self,path):
        xprv = keyTree().getChildpriKey(self.obj,path)
        xprv_hex = base58check.b58decode(xprv["xprv"])
        prikey_hex = xprv_hex[46:78].hex()
        
        path = self.obj["path"] + "/" + path
        pubkey = self.getPubkey(prikey_hex)
        addr = self.getAddr(pubkey)
        return {"path":path,"wif":prikey_hex,"addr":addr}

    def getPubkey(self,prikey):
        sk = ecdsa.SigningKey.from_string( bytes.fromhex(prikey), curve=ecdsa.SECP256k1)    
        vk = sk.get_verifying_key() #this is your verification key (public key)
        public_key = vk.to_string("compressed").hex()
        return public_key

    def getAddr(self,pubkey):
        vk = ecdsa.VerifyingKey.from_string( bytes.fromhex(pubkey), curve=ecdsa.SECP256k1)
        public_key = vk.to_string("uncompressed")

        k = keccak_256()
        k.update(bytes.fromhex(public_key.hex()[2:]))

        addr20bytes = k.hexdigest()[-40:]
        data = "41" + addr20bytes
        sha256_1 = hashlib.new('sha256',bytes.fromhex(data))
        sha256_2 = hashlib.new('sha256',bytes.fromhex(sha256_1.hexdigest()))
        addr = base58check.b58encode(bytes.fromhex(data+(sha256_2.hexdigest())[0:8]))
            
        return addr.decode('utf-8')


def main():
    xprv = "xprvA1huQ1umvqA4bbVoTkJawLmyd2FKAvXLj3WmHfvoKFDbd8t3pV5c7tVU2qE1nH7DJn2u368ggf3A2kgFRBkwJboft3sRDdMfh5jciekDzdu"
    

if __name__ == '__main__':
    main()
